<template>
  <div>
    <!-- 属性组件主体区域 -->
    <div>
      <el-tree
        ref="tree"
        :data="treedata"
        :props="{ label: 'name' }"
        show-checkbox
        default-expand-all
        check-strictly
        node-key="id"
        check-on-click-node
      />
    </div>

    <el-row class="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="cancelButton">取 消</el-button>
        <el-button
          size="small"
          type="primary"
          @click="setRolesBtn"
        >确 定</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
// 根据id,获取当前用户的权限
import { getRoleId } from '@/api/setting'
// 获取权限列表api
import { getPermissionList } from '@/api/permission'
// 属性组件处理函数
import { tranListToTreeData } from '@/utils/index'
// 给角色分配权限api
import { assignPerm } from '@/api/setting'
export default {
  name: 'AssignPermission',
  props: {
    roleId: {
      type: [Number, String],
      required: true
    }
  },
  data() {
    return {
      treedata: []
    }
  },
  created() {
    this.getPermissionList()
    this.getRoleId()
  },
  methods: {
    // 根据用户id,获取当前用户的权限
    async getRoleId() {
      const res = await getRoleId(this.roleId)
      this.$refs.tree.setCheckedKeys(res.data.permIds)
    },
    // 获取权限列表
    async getPermissionList() {
      const res = await getPermissionList()
      this.treedata = tranListToTreeData(res.data, '0')
    },
    // 取消按钮
    cancelButton() {
      this.$emit('close')
    },

    // 设置权限按钮
    async setRolesBtn() {
      const permIds = this.$refs.tree.getCheckedKeys()
      const res = await assignPerm({
        id: this.roleId,
        permIds
      })
      this.$message.success(res.message)
      this.getPermissionList()
      this.$emit('closero')
    }
  }
}
</script>

<style lang="scss" scoped>
.footer {
  margin-top: 30px;
}
</style>
